import uuid
from lxml import etree
from pymysql import Connection

import requests

# 获取指定地区和页码的电影院网页源码
def get_cinema(area, pageNo, headers):
    """
    获取指定地区的所有影院
    :param area: 地区
    :param pageNo: 展示第几页数据
    :return: 返回list集合
    """
    params = {
        'cinemaName': '',
        'pageSize': '10',
        'pageLength': '8',
        'sortType': '0',
        'n_s': 'new',
        'page': pageNo,
        'regionName': area
    }
    url = 'https://dianying.taobao.com/ajaxCinemaList.htm?'

    response = requests.get(url=url, params=params, headers=headers)
    return response

# 解析电影院网页源码
def parse_cinema(response):
    """
    对获取的cinema页面源码进行解析
    :param response: 页面源码
    :return: list<Cinema>
    """
    tree = etree.HTML(response.text)
    list_cinema = list()
    # 获取影院名称
    names = tree.xpath('//li/div[@class="detail-middle"]/div/h4/a/text()')
    # 获取影院地址
    addrs = tree.xpath('//li/div[@class="detail-middle"]/div[@class="middle-p"]/div/span/text()')
    # 获取影院电话
    teleps = tree.xpath(
        '//li/div[@class="detail-middle"]/div[@class="middle-p"]/div[@class="middle-p-list"]/text()')
    # 获取影院评分
    scores = tree.xpath('//div[@class="detail-right"]/div/strong/text()')
    # 将电影院封装成对象返回
    index = 0
    while index < len(names):
        c_id = uuid.uuid1().hex
        cinema = Cinema(c_id, names[index], addrs[index], teleps[index], scores[index])
        index += 1
        list_cinema.append(cinema)
    return list_cinema

# 将电影院信息存入数据库
def save_cinema_in_mysql(cinema_list):
    """
    将电影院信息存入数据库
    :param cinema_list: 电影院对象集合
    :return: None
    """
    # 构建Mysql数据库的连接
    conn = Connection(
        host='localhost',  # 主机名
        port=3306,  # 端口号
        user="root",  # 用户名
        password="admin"  # 密码
    )
    # 获取游标对象
    cursor = conn.cursor()
    # 选择数据库
    conn.select_db("spider")
    # 执行sql
    for cinema in cinema_list:
        sql = "insert into t_cinema values('" + cinema.c_id + "','" + cinema.c_name + "','" + cinema.c_addr + "','" + cinema.c_telep + "','" + cinema.c_score + "')"
        cursor.execute(sql)
    # 通过commit提交
    conn.commit()
    # 关闭连接
    conn.close()

class Cinema:

    def __init__(self, c_id, c_name, c_addr, c_telep, c_score):
        """
        构造方法
        :param c_id: 唯一标识id
        :param c_name: 电影院名称
        :param c_addr: 电影院地址
        :param c_telep: 电影院电话
        :param c_score: 电影院评分
        :return: None
        """
        self.c_id = c_id
        self.c_name = c_name
        self.c_telep = c_telep
        self.c_addr = c_addr
        self.c_score = c_score

    def __str__(self):
        return (self.c_id + "-" + self.c_name + "-" + self.c_telep + "-" + self.c_addr + "-" + self.c_score)
